function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json) {
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name +
                      '</a> Phone: (' + json.tmpo_poc_phone.substr(0,3) +
                      ') ' + json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    );
}


function getVehicle() {
    $.ajax({
        type: 'GET',
        url: '/api/tmpo/vehicles/' + $.qs('id') + '/',
        dataType: "json",
        success: function(json) {
            var vehicle = {};
            vehicle['id'] = json['vehicles'][0]['id'];
            vehicle['vehicleno'] = json['vehicles'][0]['vehicleno'];
            getMonth(vehicle);
        },
        error: function() {
            window.location.href = "/tmpo/";
        }
    });
}


function getMonth(vehicle, val) {
    var url = '/api/dates/month/';
    if (val){ 
        url += val + '/';
    }else if ( $.qs('date') ){
        url += $.qs('date') + '/';
    }
    $.getJSON(
        url,
        function(json) {
            $("#vehicleHistoryTable, #return").remove();
            $("div.mainContent").append(proto_html['history']);
            json = json['info'][0];
            $("#vehicleHistoryTable caption").append(vehicle['vehicleno']);
            $("#vehicleHistoryTable caption span.captionDate a:first")
                .after('&nbsp;' + json['display'] + '&nbsp;');
            for (var i = 1 ; i <= json['number_of_days']; i++){
                $("#vehicleHistoryTable").append(proto_html['day']);
                var day = i.toString() + ' ';
                if ( day.length < 3 ){
                    day = '0' + day;
                }
                $("#vehicleHistoryTable tbody:last tr td:eq(0)")
                    .append(day + json['display']);
                day = i.toString();
                if ( day.length < 2 ){
                    day = '0' + day;
                }
                day = json['current'] + '-' + day;
                var link = "/tmpo/vehicles/form1970/?id=" + vehicle['id'] +
                           "&date=" + day;
                $("#vehicleHistoryTable tbody:last")
                    .attr("date",day)
                    .find("tr td:nth-child(2) a")
                    .attr("href",link);
            }
            $("#vehicleHistoryTable tbody:odd")
                .addClass('tableAlternateColor');
            var start = json['current'] + '-01';
            var finish = json['current'] + '-' +
                         json['number_of_days'].toString();
            getHistory(vehicle, start, finish, json['previous'], json['next']);
        }
    );
}


function getHistory(vehicle, start, finish, prev, next) {
    var url = '/api/tmpo/vehicles/history/' + vehicle['id'] + '/' +
              start + '/' + finish + '/';
    $.getJSON(
        url,
        function(json) {
            json = json['history'];
            $.each(json, function() {
                var h = this;
                var sel = "#vehicleHistoryTable tbody[date='" +
                          h['dd1970_date'].substr(0,10) + "'] tr";
                var op = h['operators'].split(",").slice(0, -1);
                var de = h['destination'].split(",").slice(0, -1);
                $(sel)
                    .find("td:nth-child(2) img")
                    .attr("src","/tmpo/images/icons/form_done.gif")
                    .end()
                    .find("td:nth-child(3)")
                    .html(h['miles'])
                    .end()
                    .find("td:nth-child(4)")
                    .html(h['fuel'])
                    .end()
                    .find("td:nth-child(5)")
                    .html(h['oil'])
                    .end()                    
                    .find("td:nth-child(6)")
                    .html(op.join(", "))
                    .end()
                    .find("td:nth-child(7)")
                    .html(de.join(", "));
            });
            $("#button_previous").click( function() {
                getMonth(vehicle, prev);
                return false;
            });
            $("#button_next").click( function() {
                getMonth(vehicle, next);
                return false;
            });
            $("#button_print").unbind();
            $("#button_print").click( function() {
                historyPrint();
                return false;
            });
        }
    );
}


function historyPrint() {
    $("#vehicleHistoryTable thead tr th:nth-child(2)").remove();
    $("#vehicleHistoryTable tbody tr td:nth-child(2)").remove();
    makePrinter("#vehicleHistoryTable")();
}


function setProtoHTML() {    
    var proto_pre = {
        'history':'protoVehicleHistoryTableHTML',
        'day':'protoDayRowHTML'
    };
    proto_html = {};
    $.each(proto_pre, function(i, v) {
        proto_html[i] = $("#" + v).html();
        $("#" + v).remove();
    });
}


jQuery(function($) {
    getSiteCfg();
    setProtoHTML();
    getVehicle();
    $(":radio, :checkbox").css("border", "none");
    $("#logoutNavButton").click( function() {
        $.post("/api/logout/", {},
            function() {
                window.location.href = "/tmpo/";   
            }
        );
    });
    if ($.cookie("tmpoHome")) {
        $("img.headerLogo").parent().attr('href', $.cookie("tmpoHome"));
    }
});